from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings
import json
from sts.sts import Sts


def creat_bucket(bucket, region='ap-chengdu'):
    # 替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
    config = CosConfig(Region=region, SecretId=settings.COS_ID, SecretKey=settings.COS_KEY)
    client = CosS3Client(config)
    # 存储桶名称不支持大写字母，COS 后端会将用户传入的大写字母自动转换为小写字母用于创建存储桶
    response = client.create_bucket(
        Bucket=bucket,
        ACL='public-read',  # 设置存储桶的读写权限，例 'private'，'public-read'，'public-read-write'
    )
    return response


def bucket_cors(bucket, region='ap-chengdu'):
    """ 设置桶的跨域策略 """
    config = CosConfig(Region=region, SecretId=settings.COS_ID, SecretKey=settings.COS_KEY)
    client = CosS3Client(config)
    response = client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration={
            'CORSRule': [
                {
                    'MaxAgeSeconds': 500,
                    'AllowedOrigin': "*",  # 允许所有域名
                    'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                    'AllowedHeader': '*',
                    'ExposeHeader': '*',
                }
            ]
        },
    )


def upload_bucket(bucket, Body, Key, region='ap-chengdu'):
    config = CosConfig(Region=region, SecretId=settings.COS_ID, SecretKey=settings.COS_KEY)
    client = CosS3Client(config)
    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=Body,
        Key=Key,
    )
    return 'https://{}.cos.{}.myqcloud.com/{}'.format(bucket, region, Key)


def delete_one(bucket,Key,region='ap-chengdu'):
    config = CosConfig(Region=region, SecretId=settings.COS_ID, SecretKey=settings.COS_KEY)
    client = CosS3Client(config)
    response = client.delete_object(
        Bucket=bucket,
        Key=Key
    )

def get_credential_demo(bucket, region='ap-chengdu'):
    config = {
        # 请求URL，域名部分必须和domain保持一致
        # 使用外网域名时：https://sts.tencentcloudapi.com/
        # 使用内网域名时：https://sts.internal.tencentcloudapi.com/
        # 'url': 'https://sts.tencentcloudapi.com/',
        # 域名，非必须，默认为 sts.tencentcloudapi.com
        # 内网域名：sts.internal.tencentcloudapi.com
        'domain': 'sts.tencentcloudapi.com',
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        'secret_id': settings.COS_ID,
        # 固定密钥
        'secret_key': settings.COS_KEY,
        # 设置网络代理
        # 'proxy': {
        #     'http': 'xx',
        #     'https': 'xx'
        # },
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': "*",
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            # 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload'
        ],
        # 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
        # "condition": {
        #     "ip_equal":{
        #         "qcs:ip":[
        #             "10.217.182.3/24",
        #             "111.21.33.72/24",
        #         ]
        #     }
        # }
    }
    try:
        sts = Sts(config)
        response = sts.get_credential()
        print('get data : ' + json.dumps(dict(response), indent=4))
        return response
    except Exception as e:
        print(e)
        return e